import axios from 'axios'
import { ShowLoading, ShowSuccess } from '../utils/message';
import { ShowError } from './../utils/message';
import router from '../router/index'


export const baseURL = 'http://localhost:3000/'

const request = axios.create({
    baseURL: baseURL,
    timeout: 60000,
    headers: {  // 请求头  token 

    }
});


// Interceptors 拦截器 

request.interceptors.request.use(function (config: any) {
    // 发送之前调起Loading 
    const token = sessionStorage.getItem('token') || ''
    if (token) {
        config.headers.token = token
    }

    ShowLoading()
    return config;
}, function (error) {
    // 发送失败 
    ShowError('网络异常')
    return Promise.reject(error);
});

request.interceptors.response.use(function (response) {
    console.log(response.data)
    if (response.data.code == 200) {
        ShowSuccess(response.data.msg)
    } else {
        ShowError(response.data.msg)
        if (response.data.code == 3001) {

            router.replace({ name: 'login' })
        }
    }

    return response;
}, function (error) {

    ShowError('服务器异常 - 未知错误')
    return Promise.reject(error);
});



export const GetAction = (url: string, params?: object, headers?: object) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: 'GET',
            params: params,
            headers,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}


export const PostAction = (url: string, data?: object, params?: object, headers?: object) => {
    return new Promise((resolve, reject) => {
        request({
            url,
            method: 'POST',
            data: data,
            params: params,
            headers,
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export default request;